#include "qcustomlistview.h"

QCustomListView::QCustomListView(QWidget *parent)
        : QListView(parent)
{
    connect(this,SIGNAL(activated(QModelIndex)), this, SLOT(thisActivated(QModelIndex)));
}

QCustomListView::~QCustomListView()
{
}

void QCustomListView::mousePressEvent ( QMouseEvent * event )
{   QModelIndex indexx = this->indexAt(event->pos());
    QListView::mousePressEvent(event);
    if(!indexx.isValid())
    {   clearSelection();
    }
    emit setActive(this);
}

void QCustomListView::thisActivated(QModelIndex index)
{
    if(((QFileSystemModel*)this->model())->isDir(index))
    {   reindexFileView(index);
    }
    else
    {   QDesktopServices::openUrl(QUrl::fromLocalFile(((QFileSystemModel*)this->model())->fileInfo(index).absoluteFilePath()));
    }
}

void QCustomListView::reindexFileView(QModelIndex index)
{
    QFileSystemModel* fsm = ((QFileSystemModel*)this->model());
    if(!fsm->isDir(index))
        return;

    //TODO:optimize
    QString location(fsm->filePath(index));
    QStringList dirsplit = location.split("/");
    QString link;
    QStringList dirLink;

    for(int i=0; i<dirsplit.size(); i++)
    {   link = "<a href=\"";
        for(int j=0;j<=i;j++)
        {   link.append(dirsplit.at(j));
            link.append("/");
        }
        link.append("\">"+dirsplit.at(i)+"</a>");
        dirLink.append(link);
    }
    location = dirLink.join("/");

    //TODO: optimize
    QWidget *qwp = this->parentWidget();
    if(qwp)
    {
        QObjectList qol = qwp->children();
        for(int i=0;i<qol.size(); i++)
        {   QObject* qo = qol.at(i);
            //QMessageBox::information(this,"name",qo->objectName(),QMessageBox::Ok);
            if( qo->objectName().contains("lblPane") )
            {   ((QLabel*)qo)->setText(location);
            }
        }
    }

    this->setRootIndex(index);
}
